<?php


/**
* Puree CMS
* http://www.molotsoft.ru
*
* @package Puree_CMS
* @subpackage Admin/Behaviors
* @author Ivan Chistyakov <ivan@molotsoft.ru>
* @version $Id: field_name_slug.php 1038 2010-03-23 13:45:00Z molotsoft@gmail.com $
* @link $HeadURL: http://puree-cms.googlecode.com/svn/trunk/plugins/admin/models/behaviors/field_name_slug.php $
*/


class FieldNameSlugBehavior extends ModelBehavior {

/******************************************************************************/

var $settings = array();

/******************************************************************************/

function setup(&$Model, $settings = array()) {
	$this->settings[$Model->name] = (array)$settings;
}

/******************************************************************************/

function _strictSlug(&$Model, $value) {
	App::import('Vendor', 'Translit', array('file' => 'translit' . DS . 'translit.php'));
	$value = Inflector::slug(Translit::replace($value));
	return !empty($value) ? $value : NULL;
}

/******************************************************************************/

function getSlug(&$Model, $id = NULL) {
	return $Model->hasField('slug') ? (string)$Model->getField('slug', $id) : NULL;
}

function setSlug(&$Model, $value, $id = NULL) {
	return $Model->hasField('slug') ? $Model->setField('slug', $this->_strictSlug($Model, (string)$value), $id) : FALSE;
}

function nullSlug(&$Model, $id = NULL) {
	return $Model->hasField('slug') ? $Model->setField('slug', NULL, $id) : FALSE;
}

/******************************************************************************/

function beforeSave(&$Model) {
	$creating = empty($Model->id) && (!isset($Model->data[$Model->name][$Model->primaryKey]) || empty($Model->data[$Model->name][$Model->primaryKey]));
	if ($Model->hasField('slug')) {
		if (isset($Model->data[$Model->name]['slug'])) {
			$Model->data[$Model->name]['slug'] = $this->_strictSlug($Model, $Model->data[$Model->name]['slug']);
		} elseif ($creating && (!isset($Model->data[$Model->name]['slug']) || empty($Model->data[$Model->name]['slug']))) {
			$Model->data[$Model->name]['slug'] = NULL;
		}
	}
}

function afterSave(&$Model, $created) {
	if ($Model->hasField('slug')) {
		if ($created && (!isset($Model->data[$Model->name]['slug']) || empty($Model->data[$Model->name]['slug']))) {
			$this->setSlug($Model, $Model->name . $Model->id, $Model->id);
		}
	}
}

/******************************************************************************/

}


?>